import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:talk/pages/device/model/ShareModel.dart';
import 'package:talk/pages/device/x_device_router.dart';

import '../../api/DeviceApi.dart';
import '../../api/ShareApi.dart';
import '../../api/UserApi.dart';
import '../../api/dio/DioClient.dart';
import '../../commponets/ItemView.dart';
import '../../home/AppLocale.dart';
import '../../routers/fluro_navigator.dart';
import '../../tools/widgets/my_app_bar.dart';
import '../../utils/toast_utils.dart';
import '../my/model/UserModel.dart';
import '../provider/CustomBottomPicker.dart';
import 'model/Device.dart';


class DeviceSpecificsPage extends StatefulWidget {
  const DeviceSpecificsPage({
    super.key,
    this.deviceId,
    this.shareId,
    this.toId,
    this.nickName,
  });

  final int? deviceId;
  final int? shareId;
  final int? toId;
  final String? nickName;




  @override
  State<DeviceSpecificsPage> createState() => _DeviceSpecificsPageState();
}

class _DeviceSpecificsPageState extends State<DeviceSpecificsPage> {
  final UserApi _userApi = UserApi();
  final ShareApi _shareApi = ShareApi();
  late int _deviceId;
  late int _shareId;
  late int _toId;

  UserModel? _UserModel;
  ShareModel? _shareModel;
  late String _avatar = "http://43.139.39.5:82/pho/face/default.jpg";
  late String _nickName = "";
  late String _endTime = "";

  @override
  void initState() {
    super.initState();
    _deviceId = widget.deviceId!;
    _shareId = widget.shareId!;
    _toId = widget.toId!;

    _fetchData();
  }


  Future<void> _fetchData() async {
    try {
      final responseUser = await _userApi.getUser(_toId);

      final responseShare = await _shareApi.getShareInfo(_shareId);
      if (responseUser.code == 200) {
        setState(() {
          _UserModel = UserModel.fromJson(responseUser.data);
          if (_UserModel != null) {
            if(_UserModel?.avatar != null && _UserModel?.avatar != ""){
              _avatar = DioClient.baseUrl + _UserModel!.avatar!;
            }

            _nickName = _UserModel!.userName!;
          }
        });
      } else {
        AppLocale.text('s_500');
      }

      if (responseShare.code == 200) {
        setState(() {
          _shareModel = ShareModel.fromJson(responseShare.data);
          if (_shareModel != null) {
            if(_shareModel?.endTime != null && _shareModel?.endTime != ""){
              _endTime =  _shareModel!.endTime!;
            }else{
              _endTime = "2025-01-01";
            }

          }
        });
      } else {
        AppLocale.text('s_500');
      }

    } catch (e) {
      AppLocale.text('s_get500');;
    }
  }




  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(
        centerTitle: '分享详情',
        backgroundColor: Colors.transparent,
        dropdownWidth: 140,
        dropdownBackgroundColor: Colors.white,
        dropdownBorderRadius: 20,
      ),


      body: Container(
          child: Column(
            children: [

              const SizedBox(height: 20,),

              ItemView(
                width: 400,
                height: 50,
                leftPadding: 10,
                rightPadding: 20,
                leftWidget: Row(
                  children: [
                    const SizedBox(width: 10),
                    const Text(
                      "头像",
                      style: TextStyle(
                          fontSize: 15.0,
                          color: Colors.black
                      ),
                    ),
                  ],
                ),
                rightWidget: Row(
                  children: [
                    const SizedBox(width: 10),
                    CircleAvatar(
                      radius: 18,
                      backgroundColor: Colors.grey[200],
                      child: ClipOval(
                        child: Image.network(
                          _avatar,
                          width: 45,
                          height: 45,
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                    const SizedBox(width: 15),
                    // Icon(
                    //     Icons.arrow_forward_ios,
                    //     color: Colors.grey,
                    //     size: 14
                    // ),
                  ],
                ),
                borderRadius: 8,
                onTap: () {

                },
              ),


              ItemView(
                width: 400,
                height: 50,
                leftPadding: 10,
                rightPadding: 20,
                leftWidget: Row(
                  children: [
                    const SizedBox(width: 10),
                    const Text(
                      "昵称",
                      style: TextStyle(
                          fontSize: 15.0,
                          color: Colors.black
                      ),
                    ),
                  ],
                ),
                rightWidget: Row(
                  children: [
                    Text(
                      _nickName,
                      style: TextStyle(
                          fontSize: 14.0,
                          color: Colors.black54
                      ),
                    ),
                    const SizedBox(width: 15),
                    // Icon(
                    //     Icons.arrow_forward_ios,
                    //     color: Colors.grey,
                    //     size: 14
                    // ),
                  ],
                ),
                borderRadius: 8,
                onTap: () {
                },
              ),

              const SizedBox(height: 20),

              ItemView(
                width: 400,
                height: 50,
                leftPadding: 10,
                rightPadding: 20,
                leftWidget: Row(
                  children: [
                    const SizedBox(width: 10),
                    const Text(
                      "有效期",
                      style: TextStyle(fontSize: 15.0, color: Colors.black),
                    ),
                  ],
                ),
                rightWidget: Row(
                  children: [
                    Row(
                      children: [
                        Text(() {
                            if (_shareModel == null) return '';
                            if (_shareModel!.shareType == 0) return '永久有效';
                            if (_shareModel!.shareType == 1) return _shareModel!.endTime.toString();
                            return '';
                          }(),
                          style: TextStyle(
                              fontSize: 14.0,
                              color: Colors.black54
                          ),
                        ),
                        const SizedBox(width: 5,),
                        const Icon(
                          Icons.arrow_forward_ios,
                          color: Colors.grey,
                          size: 14,
                        ),
                      ],
                    )
                  ],
                ),
                borderRadius: 8,
                onTap: () {

                  // NavigatorUtils.push(
                  //   context,
                  //   '${XDeviceRouter.specificsSelectPage}?shareId=$_shareId&endTime=$_endTime',
                  // );

                  // 调用带返回值的pushResult方法
                  NavigatorUtils.pushResult(
                    context,
                    '${XDeviceRouter.specificsSelectPage}?shareId=$_shareId&endTime=$_endTime',
                        (result) {  // 页面返回时触发
                      // 无论返回什么结果，都刷新数据
                      _fetchData();
                    },
                  );

                },
              ),


              const SizedBox(height: 20),


              ItemView(
                width: 400,
                height: 50,
                leftPadding: 10,
                rightPadding: 20,
                leftWidget: Row(
                  children: [
                    const SizedBox(width: 10),
                    const Text(
                      "权限设置",
                      style: TextStyle(fontSize: 15.0, color: Colors.black),
                    ),
                  ],
                ),
                rightWidget: Row(
                  children: [
                    Row(
                      children: [
                        Text(
                              () {
                            if (_shareModel == null) return '';

                            // 收集所有权限为1的选项
                            List<String> permissions = [];

                            if (_shareModel!.authLock == 1) {
                              permissions.add("开锁");
                            }
                            if (_shareModel!.authTalk == 1) {
                              permissions.add("对讲");
                            }
                            if (_shareModel!.authMachine == 1) {
                              permissions.add("机器");
                            }

                            // 用逗号连接所有权限
                            return permissions.join("、");
                          }(),
                          style: const TextStyle(
                              fontSize: 14.0,
                              color: Colors.black54
                          ),
                        ),
                        const SizedBox(width: 5,),
                        const Icon(
                          Icons.arrow_forward_ios,
                          color: Colors.grey,
                          size: 14,
                        ),
                      ],
                    )
                  ],
                ),
                borderRadius: 8,
                onTap: () {
                  // 初始选中的值（根据当前权限状态）
                  List<dynamic> initialValues = [];
                  if (_shareModel != null) {
                    if (_shareModel!.authLock == 1) initialValues.add(0);
                    if (_shareModel!.authTalk == 1) initialValues.add(1);
                    if (_shareModel!.authMachine == 1) initialValues.add(2);
                  }

                  // 选项列表（label是显示文案，value是标识值）
                  List<Map<String, dynamic>> permissionList = [
                    {'label': '开锁', 'value': 0},
                    {'label': '对讲', 'value': 1},
                    {'label': '机器', 'value': 2},
                  ];

                  showModalBottomSheet(
                    context: context,
                    backgroundColor: Colors.transparent,
                    builder: (BuildContext dialogContext) {
                      return CustomBottomPicker(
                        title: "权限设置",
                        height: 300,
                        list: permissionList,
                        selectedColor: Colors.blue,
                        backgroundColor: Colors.white,
                        initialValue: initialValues, // 初始选中值（多选需要传列表）
                        selectedShapeType: SelectedShapeType.hollowCircle,
                        isMultiSelect: true, // 开启多选模式
                        onSelect: (newValues) {  // 移除List<dynamic>类型声明
                          // 选中值变化时的回调
                          setState(() {
                            // 更新权限状态
                            if (_shareModel != null) {
                              _shareModel!.authLock = newValues.contains(0) ? 1 : 0;
                              _shareModel!.authTalk = newValues.contains(1) ? 1 : 0;
                              _shareModel!.authMachine = newValues.contains(2) ? 1 : 0;
                            }

                            // 打印选中结果
                            // print("选中的权限:");
                            // print("开锁: ${newValues.contains(0) ? 1 : 0}");
                            // print("对讲: ${newValues.contains(1) ? 1 : 0}");
                            // print("机器: ${newValues.contains(2) ? 1 : 0}");


                            final toUpdate = {
                              "shareId": _shareId,
                              "authLock": newValues.contains(0) ? 1 : 0,
                              "authTalk": newValues.contains(1) ? 1 : 0,
                              "authMachine": newValues.contains(2) ? 1 : 0,
                            };
                            _shareApi.updateShareAuth(toUpdate);
                          });
                        },
                      );
                    },
                  );
                },
              ),


              //自动推到最下方
              Expanded(child: Container()),

              //底部确认按钮
              Padding(
                padding: const EdgeInsets.all(20.0),
                child: SizedBox(
                  width: double.infinity,
                  height: 50,
                  child: ElevatedButton(
                    onPressed: (){

                      BrnDialogManager.showConfirmDialog(context,
                          title: "移除分享",
                          cancel: '取消',
                          confirm: '确定',
                          message: "是否移除改人员分享？",
                          onConfirm: () async {
                            // 1. 添加 async 关键字
                            // 执行删除接口（如果接口是异步的，建议加 await 等待删除完成）
                            final response = await _shareApi.deleteById(_shareId).timeout(
                              const Duration(seconds: 10),
                            );

                            if(response.code == 200){
                              Toast.show("移除成功");
                              Navigator.pop(context);
                              await Future.delayed(Duration(seconds: 1));

                              Navigator.maybePop(context);
                            }else{
                              Toast.show(response.msg ?? "移除失败");
                              Navigator.pop(context);
                            }
                          },
                          onCancel: () {
                            // BrnToast.show("取消", context);
                            Navigator.pop(context);
                      });


                    },
                    style: ElevatedButton.styleFrom(
                      backgroundColor: Colors.red,
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    child: const Text(
                      "移除分享",
                      style: TextStyle(
                        fontSize: 16,
                        color: Colors.white,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          )
      ),
    );
  }

}



























